package com.fengxu.gamescript.ui.base

import android.content.Intent
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import androidx.appcompat.app.AppCompatActivity
import com.fengxu.gamescript.ui.error.ErrorReportActivity
import org.jetbrains.anko.toast
import org.mozilla.javascript.ast.Loop
import java.util.*
import kotlin.properties.Delegates

open class BaseActivity : AppCompatActivity() {

    // 按下返回键的模式，一次退出或两个退出
    enum class BackMode{
        One,Two
    }

    // 用户触发退出的模式，退出当前activity或整个程序
    enum class ExitMode{
        Current,All
    }

    // 用户点击退出键的触发模式
    protected var backMode:BackMode = BackMode.One

    // 用户退出时，触发的是退出当前页还是整个程序
    protected var exitMode:ExitMode = ExitMode.Current

    companion object{
        // 所有activity
        val aliveActivityList = Vector<BaseActivity>()

        // uiHandler
        val uiHandler: Handler by lazy {
            synchronized(BaseActivity::class.java){
                Handler(Looper.getMainLooper())
            }
        }

        // 获取当前存在的activity实例
        inline fun <reified T : BaseActivity> findActivity(): T? {
            val res:BaseActivity? = aliveActivityList.find { it.javaClass == T::class.java }
            if(res != null){
                return res as T
            }
            return null
        }

        fun exitAll(){
            aliveActivityList.forEach {
                it.finish()
                System.exit(0)
            }
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        aliveActivityList.add(this)
        Thread.setDefaultUncaughtExceptionHandler(GlobalUnCatchExceptionHandler())
        super.onCreate(savedInstanceState)
    }

    override fun onDestroy() {
        aliveActivityList.remove(this)
        super.onDestroy()
    }

    private var startTime = 0L

    override fun onBackPressed() {
        val exit = {
            if(exitMode == ExitMode.Current){
                super.onBackPressed()
                finish()
            }else{
                exitAll()
            }
        }
        if(backMode == BackMode.One){
            exit()
        }else{
            val secondTime = System.currentTimeMillis()
            if(secondTime - startTime > 2000){
                toast("""两秒内再按一次退出${if(exitMode == ExitMode.All){"程序"}else{"当前页"}}""")
                startTime = secondTime
            }else{
                exit()
            }
        }
    }

    /**
     * 自定义全局异常捕获
     */
    private inner class GlobalUnCatchExceptionHandler: Thread.UncaughtExceptionHandler {

        override fun uncaughtException(t: Thread, e: Throwable) {
            val errorMsg = " ThreadId: ${t.id} \n\n ThreadName: ${t.name} \n\n " +
                    "Activity: ${BaseActivity.aliveActivityList.lastElement()!!.javaClass} \n\n " +
                    "ErrorMsg: ${e.message ?: ""}\n\n Stack: ${e.stackTraceToString()}"
            val intent = Intent(this@BaseActivity, ErrorReportActivity::class.java)
            intent.putExtra("errorMsg", errorMsg)
            startActivity(intent)
        }

    }

}